#!/usr/bin/env python3
import requests
import sys
import argparse
import json
import hashlib
import os

__author__ = "Corsin Camichel"
__copyright__ = "Copyright 2020, Corsin Camichel"
__license__ = "Creative Commons Attribution-ShareAlike 4.0 International License."
__version__ = "1.0.1"
__email__ = "cocaman@gmail.com"

parser = argparse.ArgumentParser(description='Upload a malware sample to Malware Bazaar by abuse.ch')
parser.add_argument('-f', '--file', help='File to upload (required)', type=str, metavar="FILE", required=True)
args = parser.parse_args()

extracted_file_extension = os.path.splitext(args.file)[1].replace(".","")

tags = []
tags.append("" + extracted_file_extension + "")

delivery_method = ""

# Ask user if this came by email
is_email_attachment = input(f"Was this file received by email attachment? Y/N ")
is_email_link = input(f"Was this file received by email link? Y/N ")

if(is_email_attachment.upper() == "Y" and is_email_link.upper() == "Y"):
    delivery_method = "multiple"
elif(is_email_attachment.upper() == "Y"):
    delivery_method = "email_attachment"
elif(is_email_link.upper() == "Y"):
    delivery_method = "email_link"
else:
    delivery_method = "other"

headers = {'API-KEY': ''}
data = {
    'tags': tags,
    'delivery_method': delivery_method
}
files = {
    'json_data': (None, json.dumps(data), 'application/json'),
    'file': (open(args.file,'rb'))
}

response = requests.post('https://mb-api.abuse.ch/api/v1/', files=files, headers=headers)
json_data = json.loads(response.text)
status = json_data['query_status']

print("Upload status: " + status)
if(status == "file_already_known"):
    with open(args.file,"rb") as f:
        file_bytes = f.read()
        hash_sha256 = hashlib.sha256(file_bytes).hexdigest();
        print("The report can be found here: https://bazaar.abuse.ch/sample/" + hash_sha256 + "/")
    
#print(response.content.decode("utf-8", "ignore"))
